package com.ljf.captcha;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.ljf.captcha.vo.KaptchaVO;
import com.ljf.framework.cache.LjfCacheManager;
import com.ljf.framework.context.LjfContextManager;
import com.ljf.framework.exception.LjfException;
import com.ljf.framework.filter.LjfAbstractFilter;
import com.ljf.framework.filter.LjfFilterAuthStrategy;
import com.ljf.framework.log.LjfLogManager;
import com.ljf.framework.log.LjfLogService;
import com.ljf.framework.result.JsonResult;
import com.ljf.framework.result.JsonResultEnum;
import com.ljf.framework.router.LjfRouter;
import com.ljf.framework.router.LjfRouterConstants;
import com.ljf.framework.router.LjfRouterManager;
import com.ljf.framework.util.LjfJsonUtil;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

import static com.google.code.kaptcha.Constants.KAPTCHA_BORDER;
import static com.google.code.kaptcha.Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE;

/**
 * 说明：
 *
 * @Auther: lijinfeng
 * @Date: 2024/4/30
 */
public class CaptchaCreateFilter extends LjfAbstractFilter {
    LjfLogService logger = LjfLogManager.getLogger(CaptchaCreateFilter.class);

    @Override
    public Integer getOrder() {
        return 1;
    }

    @Override
    public List getIncludeList() {
        return Arrays.asList("/auth/kaptchaImage");
    }

    @Override
    public LjfFilterAuthStrategy getBeforeAuthStrategy() {
        return r ->true;
    }

    @Override
    public LjfFilterAuthStrategy getAuthStrategy() {
        return r -> {
            if(!CaptchaManager.getCaptchaConfig().isOpen()){
                return false;
            }
            DefaultKaptcha defaultKaptcha = getKaptchaBean();
            HttpServletResponse response = (HttpServletResponse) LjfContextManager.getResponse().getSource();
            HttpServletRequest request = (HttpServletRequest) LjfContextManager.getRequest().getSource();

            // 设置浏览器缓存机制
            response.setHeader("Cache-Control", "no-store, no-cache");
            // 设置返回响应类型
            response.setContentType("image/jpeg");
            // 生成验证码
            String code = defaultKaptcha.createText();
            // 获取当前请求的会话，将生成的验证码保存到当中
            HttpSession session = request.getSession();
            session.setAttribute("code", code);

            // 生成图片验证码
            BufferedImage image = defaultKaptcha.createImage(code);
            // 转为Base64
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            String imgString = null;
            try {
                ImageIO.write(image, "png", stream);
                imgString = "data:image/gif;base64," + Base64.getEncoder().encodeToString(stream.toByteArray());
                stream.flush();
                stream.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
            String imgKey = UUID.randomUUID().toString();
            KaptchaVO kaptchaVO = new KaptchaVO(imgKey, imgString);
            LjfCacheManager.set(CaptchaConstants.LOGIN_CAPTCHA_KEY + kaptchaVO.getKey(), code, kaptchaVO.getExpirationTime());

            // 获取PrintWriter对象
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.print(LjfJsonUtil.toJsonString(JsonResult.success(JsonResultEnum.SUCCESS, kaptchaVO)));
                // 释放PrintWriter对象
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            logger.info("获取验证码:" + code + ",缓存key：" + imgKey);
            return false;
        };
    }


    @Override
    public boolean doCusFilter() {

        return true;

    }

    /**
     * 配置 验证码规则属性
     *
     * @return
     */
    public DefaultKaptcha getKaptchaBean() {
        // 实例一个DefaultKaptcha
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        // 创建配置对象
        Properties properties = new Properties();
        // 设置边框
        properties.setProperty(KAPTCHA_BORDER, "yes");
        // 设置颜色
        properties.setProperty("kaptcha.border.color", "105,179,90");
        // 设置字体颜色
        properties.setProperty("kaptcha.textproducer.font.color", "blue");
        // 设置宽度
        properties.setProperty("kaptcha.image.width", "125");
        // 高度
        properties.setProperty("kaptcha.image.height", "38");
        // 验证码文本字符大小 默认为40
        properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "33");
        // 设置session.key
        properties.setProperty("kaptcha.session.key", "code");
        // 设置文本长度
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        // 设置字体
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        // 将以上属性设置为实例一个DefaultKaptcha的属性
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        // 将defaultKaptcha返回
        return defaultKaptcha;
    }


}
